<template>
    <el-form :model="formData" style="min-height: 680px;padding: 20px;">
      <div v-for="(item, index) in formData.keyValuePairs" :key="index">
        <el-form-item>
          <el-input v-model="item.key" placeholder="键" style="width: 200px; margin-right: 10px;"></el-input>
          <el-input v-model="item.value" placeholder="值" style="width: 200px; margin-right: 10px;"></el-input>
          <el-input v-model="item.remarks" placeholder="说明备注" style="width: 200px; margin-right: 10px;"></el-input>
          <el-button type="danger" @click="removeKeyValue(index)" :disabled="formData.keyValuePairs.length <= 1">
            删除
          </el-button>
        </el-form-item>
      </div>
      <el-button type="primary" @click="addKeyValue">添加配置项</el-button>
      <el-button type="success" @click="submitForm" style="margin-left: 20px;">提交</el-button>
    </el-form>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  // 确保导入的名称与 `configService.js` 文件中的导出一致
  import { configService} from '@/api/configService'; 
  
  const formData = ref({
    keyValuePairs: [
      { key: '', value: '', remarks: '' }
    ]
  });

  const getConfigList = async () => {
    try {
      const res = await configService.getList();
      console.log('获取配置列表:', res);
     
        formData.value.keyValuePairs = res;
      
      
    } catch (error) {
      ElMessage.error('获取配置列表失败');
      console.error('Error fetching config list:', error);
    }
  };

  getConfigList();
  
  const addKeyValue = () => {
    formData.value.keyValuePairs.push({ key: '', value: '', remarks: '' });
  };
  
  const removeKeyValue = (index) => {
    if (formData.value.keyValuePairs.length > 1) {
      formData.value.keyValuePairs.splice(index, 1);
    }
  };
  
  const submitForm = () => {
    // 过滤掉空键值对
    const nonEmptyPairs = formData.value.keyValuePairs.filter(
      item => item.key.trim() !== '' || item.value.trim() !== '' || item.remarks.trim() !== ''
    );
    
    if (nonEmptyPairs.length === 0) {
      ElMessage.warning('请至少填写一个有效的键值对');
      return;
    }
    
    // 转换为对象格式
    const result = {};
    nonEmptyPairs.forEach(item => {
      if (item.key.trim() !== '') {
        result[item.key.trim()] = item.value.trim();
      }
    });
    
    // 这里可以进行API调用
    const addResult = configService.addAdmin({"data":formData.value.keyValuePairs}).then(result => {
        ElMessage.success('提交成功');
    });

    console.log('提交的数据:', result);
    // 这里可以替换为实际的API调用
    // axios.post('/api/endpoint', result).then(...)
    
  };
  </script>
  
  <style scoped>
  .el-form-item {
    margin-bottom: 20px;
  }
  </style>